package cn.wolfcode.p2p.business.service.impl;

import cn.wolfcode.p2p.base.query.QueryObject;
import cn.wolfcode.p2p.business.domain.CreditTransfer;
import cn.wolfcode.p2p.business.domain.PaymentScheduleDetail;
import cn.wolfcode.p2p.business.mapper.CreditTransferMapper;
import cn.wolfcode.p2p.business.mapper.PaymentScheduleDetailMapper;
import cn.wolfcode.p2p.business.service.ICreditTransferService;
import cn.wolfcode.p2p.business.service.IPaymentScheduleDetailService;
import cn.wolfcode.p2p.util.AssertUtil;
import cn.wolfcode.p2p.util.Constants;
import cn.wolfcode.p2p.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
@Transactional
public class CreditTransferServiceImpl implements ICreditTransferService {
    @Autowired
    private CreditTransferMapper creditTransferMapper;
    @Autowired
    private PaymentScheduleDetailMapper paymentScheduleDetailMapper;

    @Override
    public PageInfo queryCanCreditTransfer(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<CreditTransfer> list = creditTransferMapper.selectCanCredittransfer(qo);
        return new PageInfo(list);
    }

    @Override
    public void creditTransfer(Long[] bidIds) {
        //1.判断参数
        AssertUtil.instance().isNotNull(bidIds, "无效的债权转让请求");

        //2.根据 bidId 查询出对应的可以转让的债权标
        List<CreditTransfer> readyTransfers =
                creditTransferMapper.selectReadyCreditTransForList(bidIds, UserContext.getCurrentUser().getId());
        for (CreditTransfer transfer : readyTransfers) {

            transfer.setBidRequestState(Constants.BIDREQUEST_STATE_BIDDING);
            transfer.setTransFrom(UserContext.getCurrentUser());
            transfer.setPublishDate(new Date());

            //3.然后插入到 credit_transfer表 中
            creditTransferMapper.insert(transfer);
        }

        //4.修改转让的债权标 对应的收款计划 的债权转让状态为已转让
        paymentScheduleDetailMapper
                .batchUpdateTransferState(bidIds, PaymentScheduleDetail.TRANSFER_STATE_TRANSFERING);
    }

    @Override
    public CreditTransfer getByBidIdAndTransferFromIdAndState(Long bidId, Long toLoginInfoId, int bidrequestState) {
        return creditTransferMapper.getByBidIdAndTransferFromIdAndState(bidId ,toLoginInfoId,bidrequestState);
    }

    @Override
    public void update(CreditTransfer transfer) {
        AssertUtil.instance().isFalse(0 == creditTransferMapper.updateByPrimaryKey(transfer),
                "债权信息修改失败,乐观锁异常");
    }
}
